package com.openlogic.common.logic.decision.table.engine;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.noear.nami.Nami;
import org.noear.solon.Solon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;
import com.googlecode.aviator.AviatorEvaluator;
import com.openlogic.api.logic.dto.RuleSqlModelDto;
import com.openlogic.api.logic.service.RemoteRuleModelService;
import com.openlogic.common.core.utils.DateUtils;
import com.openlogic.common.logic.cache.DefaultSqlCache;
import com.openlogic.common.logic.constants.RuleConstants;
import com.openlogic.common.logic.constants.RuleTypeConstants;
import com.openlogic.common.logic.decision.common.DecisionEngine;
import com.openlogic.common.logic.decision.common.enums.Logic;
import com.openlogic.common.logic.decision.table.constants.TableConstants;
import com.openlogic.common.logic.decision.table.model.DecisionRow;
import com.openlogic.common.logic.decision.table.model.DecisionTable;
import com.openlogic.common.logic.decision.table.model.DecisionTableResultVo;
import com.openlogic.common.logic.run.ExecRuleHandler;
import com.openlogic.common.logic.utils.StackExceptionUtils;
import com.openlogic.common.plugins.db.api.utils.DataSourceUtils;
import com.openlogic.common.plugins.spi.enums.DbType;
import com.openlogic.datasource.api.param.ConnectionParam;

import jodd.db.connection.ConnectionProvider;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
* @ClassName: XDecisionTableEngine
* @Description: 决策表执行引擎
* @author weiyongpeng
* @date 2024年9月28日 上午9:54:57
 */
public class XDecisionTableEngine extends DecisionEngine{
	
	private static RemoteRuleModelService remoteRuleModelService = Solon.context().getBean(RemoteRuleModelService.class);
	
	private static final Logger log = LoggerFactory.getLogger(XDecisionTableEngine.class);
	
	private static Object[] execLogArray = new Object[2];
	
	private static long DEFAULT_EXPIRE = 5 * 60 * 1000;
    
	private static DefaultSqlCache sqlCache = new DefaultSqlCache(100, DEFAULT_EXPIRE);
    
	private <T> T putCacheValue(String key, T value, long ttl) {
        sqlCache.put(key, value, ttl);
        return value;
    }
	
	private static final String execLogMsg = MessageFormat.format("{0} 正常信息 决策表:【开始执行】", DateUtils.formatDate(DateUtils.getNowDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));

	static {
		initExecLog(execLogArray,execLogMsg,RuleTypeConstants.decisionTable.getCode());
		if (remoteRuleModelService == null) {
			remoteRuleModelService = Nami.builder().create(RemoteRuleModelService.class);
			Solon.context().beanMake(RemoteRuleModelService.class);
		}
	}
	
	public static Object[] getExecLogArray() {
		return execLogArray;
	}

	/**
	* 描述：决策表引擎
	* @Title: parseDecisionTable
	* @param decisionTable
	* @throws Exception
	* @author weiyongpeng
	* @return 
	* @date  2024年9月28日 下午3:04:12
	 */
	public static DecisionTableResultVo doDecisionTable(DecisionTable decisionTable,Map<String, Object> params,String id,StringBuilder logs) throws Exception{
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		// 条件参数队列-条件桩
		Deque<Map<Integer, String>> conditionValueParamQueue = new ConcurrentLinkedDeque<>();
		// 动作参数队列-动作桩
		Deque<Map<Integer, String>> actionValueParamQueue = new ConcurrentLinkedDeque<>();
		// 条件参数队列-条件桩-中文
		Deque<Map<Integer, String>> conditionTextParamQueue = new ConcurrentLinkedDeque<>();
		// 动作参数队列-动作桩-中文
		Deque<Map<Integer, String>> actionTextParamQueue = new ConcurrentLinkedDeque<>();
		
		// 条件表达式队列-条件集
		Deque<Map<String, String>> conditionValueQueue = new ConcurrentLinkedDeque<>();
		// 结果表达式队列-结果集
		Deque<Map<String, String>> actionValueQueue = new ConcurrentLinkedDeque<>();
		// 条件表达式队列-条件集-中文
		Deque<Map<String, String>> conditionTextQueue = new ConcurrentLinkedDeque<>();
		// 结果表达式队列-结果集-中文
		Deque<Map<String, String>> actionTextQueue = new ConcurrentLinkedDeque<>();
		
		// 获取决策表数据集
		List<List<DecisionRow>> decisions = decisionTable.getDecisionRows();
		// 开始解析
		JSONArray decisionArrayJson = JSONArray.fromObject(decisions);
		for (Object decisionArr : decisionArrayJson) {
			JSONArray decisionRowArrayJson = JSONArray.fromObject(decisionArr);
			// 每一行的元素
			for (Object row : decisionRowArrayJson) {
				// 行号
				Integer rowNum = (Integer)JSONObject.fromObject(row).get(TableConstants.ROW_NUM_KEYWORDS);
//				log.info("\n");
//				log.info("rowNum:{} Row:{}", rowNum, row.toString());
				JSONArray decisionCellArrayJson = JSONArray.fromObject(JSONObject.fromObject(row).get(TableConstants.DECISION_CELLS_KEYWORDS));
				for (Object cell : decisionCellArrayJson) {
					// 列号
					Integer cellNum = (Integer)JSONObject.fromObject(cell).get(TableConstants.CELL_NUM_KEYWORDS);
					String cellType = (String)JSONObject.fromObject(cell).get(TableConstants.CELL_TYPE_KEYWORDS);
					String cellValue = (String)JSONObject.fromObject(cell).get(TableConstants.CELL_VALUE_KEYWORDS);
					String cellText = (String)JSONObject.fromObject(cell).get(TableConstants.CELL_TEXT_KEYWORDS);
					// 是否跨行
					Integer rowSpan = (Integer)JSONObject.fromObject(cell).get(TableConstants.ROW_SPAN_KEYWORDS);
					if (rowNum == 0 && cellType.equals(TableConstants.CellTypeEnums.PARAM_DOT_CELL.getCode())) { // 取对应的参数字段和赋值字段入队
						Map<Integer, String> conditionValueMap = new HashMap<>();
						conditionValueMap.put(cellNum, cellValue);
						Map<Integer, String> conditionTextMap = new HashMap<>();
						conditionTextMap.put(cellNum, cellText);
						conditionValueParamQueue.push(conditionValueMap);
						conditionTextParamQueue.push(conditionTextMap);
					}else if(rowNum == 0 && cellType.equals(TableConstants.CellTypeEnums.ACTION_DOT_CELL.getCode())) {
						Map<Integer, String> actionValueMap = new HashMap<>();
						actionValueMap.put(cellNum, cellValue);
						Map<Integer, String> conditionTextMap = new HashMap<>();
						conditionTextMap.put(cellNum, cellText);
						actionValueParamQueue.push(actionValueMap);
						actionTextParamQueue.push(conditionTextMap);
					}else if(rowNum > 0 && cellType.equals(TableConstants.CellTypeEnums.CONDITION_EXPR_CELL.getCode()) && rowSpan == 1) { // 没有跨行
						// 表达式
						Map<String,String> valueMap = new HashMap<>();
						generatorConditionExpress(conditionValueParamQueue, rowNum, cellNum, cellValue, valueMap);
						conditionValueQueue.push(valueMap);
						// 中文
						Map<String,String> textMap = new HashMap<>();
						generatorConditionTextExpress(conditionTextParamQueue, rowNum, cellNum, cellText, textMap);
						conditionTextQueue.push(textMap);
					}else if(rowNum > 0 && cellType.equals(TableConstants.CellTypeEnums.CONDITION_EXPR_CELL.getCode()) && rowSpan > 1) { // 跨行
						for (int j = 0; j < rowSpan; j++) {
							Map<String,String> map = new HashMap<>();
							generatorConditionExpress(conditionValueParamQueue, (j+cellNum), cellNum, cellValue, map);
							conditionValueQueue.push(map);
							// 中文
							Map<String,String> textMap = new HashMap<>();
							generatorConditionTextExpress(conditionTextParamQueue, (j+cellNum), cellNum, cellText, textMap);
							conditionTextQueue.push(textMap);
						}
					}else if(rowNum > 0 && cellType.equals(TableConstants.CellTypeEnums.ACTION_EXPR_CELL.getCode())) {
						// 执行动作参数
						Map<String,String> map = new HashMap<>();
						genactorActionExpress(actionValueParamQueue, rowNum, cellNum, cellValue, map);
						actionValueQueue.push(map);
						// 中文
						Map<String,String> textMap = new HashMap<>();
						genactorActionTextExpress(actionTextParamQueue, rowNum, cellNum, cellText, textMap);
						actionTextQueue.push(textMap);
					}
//					log.info("\n");
//					log.info("cellNum:{} cell:{}",cellNum, cell.toString());
				}
			}
		}
		// 还需要做一个转化操作
		Map<String, String> conditionMap = mapCombine(conditionValueQueue);
		Map<String, String> actionMap = mapCombine(actionValueQueue);
		Map<String, String> conditionChnMap = chnMapCombine(conditionTextQueue);
		Map<String, String> actionChnMap = chnMapCombine(actionTextQueue);
		// 执行决策表
		DecisionTableResultVo resultVo = execuate(conditionMap,actionMap,conditionChnMap,actionChnMap,params,id,logs,stopWatch);
		if(Optional.ofNullable(resultVo.getExecStatus()).isPresent() && resultVo.getExecStatus()) {
			resultVo.setStartTime(DateUtils.formatDate(new Date(stopWatch.getStartTime())));
			Object[] execLogArray = getExecLogArray();
			execLogArray[1] = resultVo;
			resultVo.setExecLog(JSONArray.fromObject(execLogArray).toString());
		}else if(Optional.ofNullable(resultVo.getExecStatus()).isPresent() && !resultVo.getExecStatus()) {
			resultVo.setStartTime(DateUtils.formatDate(new Date(stopWatch.getStartTime())));
			Object[] execLogArray = getExecLogArray();
			execLogArray[1] = resultVo;
			resultVo.setResult(JSONArray.fromObject(execLogArray).toString());
		}else {
			resultVo.setStartTime(DateUtils.formatDate(new Date(stopWatch.getStartTime())));
			Object[] execLogArray = getExecLogArray();
			resultVo.setExecLog("暂无匹配的条件");
			resultVo.setExecStatus(RuleConstants.NODE_EXEC_SUCCESS);
			execLogArray[1] = resultVo;
			resultVo.setExecLog(JSONArray.fromObject(execLogArray).toString());
		}
		return resultVo;
	}
	
	/**
	* 描述：执行决策表
	* @Title: execuate
	* @param conditionMap
	* @param actionMap
	* @param params
	* @param id
	* @param logs
	* @return
	* @author weiyongpeng
	* @date  2024年9月29日 上午11:02:51
	 */
	private static DecisionTableResultVo execuate(Map<String, String> conditionMap,Map<String, String> actionMap,
					Map<String, String> conditionChnMap,Map<String, String> actionChnMap,
					Map<String, Object> params,String id,StringBuilder logs,StopWatch stopWatch){
		DecisionTableResultVo resultVo = new DecisionTableResultVo();
		resultVo.setId(id);
		Iterator<String> condition = conditionMap.keySet().iterator();
		while (condition.hasNext()) {
			try {
				String key = condition.next();
				// 2、获取条件表达式 - 这里需要根据变量的类型，执行不同的AviatorExecutor
				String expressValue = doParseExpressValue(conditionMap.get(key), params);
				boolean result = (boolean) AviatorEvaluator.execute(expressValue, params, true);
				// 条件成立，执行
				if (result) {
					Object caclRes = Optional.of(actionMap.get(key)).isPresent() ? 
							Arrays.asList(actionMap.get(key).split(Logic.AND.toString())).stream().map(x -> 
								AviatorEvaluator.execute(doParseExpressValue(x, params), params, true)
							).collect(Collectors.toList()) 
							: "";
					stopWatch.split();
					logs.append(MessageFormat.format("决策执行id:【{0}】;决策执行开始时间:【{1}】;决策执行条件:【{2}】;决策执行动作:【{3}】;最终计算结果:【{4}】;决策执行结束时间:【{5}】;决策总耗时:【{6}】毫秒", id, DateUtils.formatDate(new Date(stopWatch.getStartTime()), DateUtils.YYYY_MM_DD_HH_MM_SS), conditionChnMap.get(key), actionChnMap.get(key), caclRes, DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS), stopWatch.getTime()));
					resultVo.setExecLog(logs.toString());
					resultVo.setExecStatus(RuleConstants.NODE_EXEC_SUCCESS);
					resultVo.setResult(caclRes);
				}
			} catch (Exception e) {
				log.error("决策表执行异常:[{}]", e);
				resultVo.setExecStatus(RuleConstants.NODE_EXEC_ERROR);
				resultVo.setResult(MessageFormat.format("决策执行id:【{0}】;决策树执行异常,异常信息:【{1}】",id, StackExceptionUtils.getExceptionType(e).toString()));
				return resultVo;
			}
		}
		return resultVo;
	}
	
	/**
	* 描述：重新组装Map
	* @Title: mapCombine
	* @param list
	* @author weiyongpeng
	* @date  2024年9月28日 下午3:07:26
	 */
	private static Map<String,String> mapCombine(Deque<Map<String, String>> list) {
		Map<String, String> map = new HashMap<>();
		for (Map<String, String> m : list) {
			Iterator<String> it = m.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				if (!map.containsKey(key)) {
					map.put(key, m.get(key));
				} else {
					map.put(key, String.join(StringUtils.SPACE + Logic.AND.toString() + StringUtils.SPACE, map.get(key),m.get(key)));
				}
			}
		}
		return map;
	}
	
	/**
	* 描述：合成中文
	* @Title: chnMapCombine
	* @param list
	* @return
	* @author weiyongpeng
	* @date  2024年9月29日 下午1:24:25
	 */
	private static Map<String,String> chnMapCombine(Deque<Map<String, String>> list) {
		Map<String, String> map = new HashMap<>();
		for (Map<String, String> m : list) {
			Iterator<String> it = m.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				if (!map.containsKey(key)) {
					map.put(key, "[" + m.get(key) + "]");
				} else {
					map.put(key, String.join(StringUtils.SPACE + "," + StringUtils.SPACE, map.get(key), "[" + m.get(key) + "]"));
				}
			}
		}
		return map;
	}

	/**
	* 描述：生成结果表达式
	* @Title: genactorActionExpress
	* @param actionValueParamQueue
	* @param rowNum
	* @param cellNum
	* @param cellValue
	* @param map
	* @author weiyongpeng
	* @date  2024年9月28日 下午3:07:26
	 */
	private static void genactorActionExpress(Deque<Map<Integer, String>> actionValueParamQueue, Integer rowNum,
			Integer cellNum, String cellValue, Map<String, String> map) {
		String actionparam = String.join("",actionValueParamQueue.stream().filter(x -> x.containsKey(cellNum))
						.map(x -> x.get(cellNum)).collect(Collectors.toList()));
		String action = cellValue.contains("=") ? String.join("", actionparam, cellValue) : String.join("=", actionparam, cellValue);
		map.put(rowNum + "", action);
	}
	
	/**
	* 描述：生成结果中文表达式
	* @Title: genactorActionTextExpress
	* @param actionValueParamQueue
	* @param rowNum
	* @param cellNum
	* @param cellValue
	* @param map
	* @author weiyongpeng
	* @date  2024年9月29日 下午1:18:05
	 */
	private static void genactorActionTextExpress(Deque<Map<Integer, String>> actionTextParamQueue, Integer rowNum,
			Integer cellNum, String cellText, Map<String, String> map) {
		String actionparam = String.join("",actionTextParamQueue.stream().filter(x -> x.containsKey(cellNum))
						.map(x -> x.get(cellNum)).collect(Collectors.toList()));
		String action = cellText.contains("等于") ? String.join("", actionparam, cellText) : String.join("等于", actionparam, cellText);
		map.put(rowNum + "", action);
	}

	/**
	* 描述：组装生成条件表达式
	* @Title: generatorConditionExpress
	* @param conditionValueParamQueue
	* @param rowNum
	* @param cellNum
	* @param cellValue
	* @param map
	* @author weiyongpeng
	* @date  2024年9月28日 下午2:30:14
	 */
	private static void generatorConditionExpress(Deque<Map<Integer, String>> conditionValueParamQueue, Integer rowNum,
			Integer cellNum, String cellValue, Map<String, String> map) throws Exception{
		if (cellValue.contains(Logic.AND.toString())) {
			String conditionExpre = String.join(
					StringUtils.SPACE + Logic.AND.toString() + StringUtils.SPACE,
					Arrays.asList(cellValue.split(Logic.AND.toString())).stream().map(i -> String
							.join("",
									conditionValueParamQueue.stream().filter(x -> x.containsKey(cellNum))
											.map(x -> x.get(cellNum)).collect(Collectors.toList()))
							.trim() + i.trim()).collect(Collectors.toList()));
			map.put(rowNum + "", conditionExpre);
		}else if(cellValue.contains(Logic.OR.toString())) {
				String conditionExpre = String.join(
						StringUtils.SPACE + Logic.OR.toString() + StringUtils.SPACE,
						Arrays.asList(cellValue.split(Logic.OR.toString())).stream().map(i -> String
								.join("",
										conditionValueParamQueue.stream().filter(x -> x.containsKey(cellNum))
												.map(x -> x.get(cellNum)).collect(Collectors.toList()))
								.trim() + i.trim()).collect(Collectors.toList()));
				map.put(rowNum + "", conditionExpre);
		}
		if(map.isEmpty()) {
			String conditionExpre = String.join(
					StringUtils.SPACE + Logic.AND.toString() + StringUtils.SPACE,
					Arrays.asList(cellValue.split(Logic.AND.toString())).stream().map(i -> String
							.join("",
									conditionValueParamQueue.stream().filter(x -> x.containsKey(cellNum))
											.map(x -> x.get(cellNum)).collect(Collectors.toList()))
							.trim() + i.trim()).collect(Collectors.toList()));
			map.put(rowNum + "", conditionExpre);
		}
	}
	
	/**
	* 描述：生成条件中文表达式
	* @Title: generatorConditionTextExpress
	* @param conditionValueParamQueue
	* @param rowNum
	* @param cellNum
	* @param cellValue
	* @param map
	* @throws Exception
	* @author weiyongpeng
	* @date  2024年9月29日 下午1:07:23
	 */
	private static void generatorConditionTextExpress(Deque<Map<Integer, String>> conditionTextParamQueue, Integer rowNum,
			Integer cellNum, String cellText, Map<String, String> map) throws Exception{
		if (cellText.contains(Logic.AND.toChnString())) {
			String conditionExpre = String.join(
					StringUtils.SPACE+ Logic.AND.toChnString() + StringUtils.SPACE,
					Arrays.asList(cellText.split(Logic.AND.toChnString())).stream().map(i -> String
							.join("",
									conditionTextParamQueue.stream().filter(x -> x.containsKey(cellNum))
											.map(x -> x.get(cellNum)).collect(Collectors.toList()))
							.trim() + i.trim()).collect(Collectors.toList()));
			map.put(rowNum + "", conditionExpre);
		}else if(cellText.contains(Logic.OR.toChnString())) {
				String conditionExpre = String.join(
						StringUtils.SPACE + Logic.OR.toChnString() + StringUtils.SPACE,
						Arrays.asList(cellText.split(Logic.OR.toChnString())).stream().map(i -> String
								.join("",
										conditionTextParamQueue.stream().filter(x -> x.containsKey(cellNum))
												.map(x -> x.get(cellNum)).collect(Collectors.toList()))
								.trim() + i.trim()).collect(Collectors.toList()));
				map.put(rowNum + "", conditionExpre);
		}
		if(map.isEmpty()) {
			String conditionExpre = String.join(
					StringUtils.SPACE+ Logic.AND.toChnString() + StringUtils.SPACE,
					Arrays.asList(cellText.split(Logic.AND.toChnString())).stream().map(i -> String
							.join("",
									conditionTextParamQueue.stream().filter(x -> x.containsKey(cellNum))
											.map(x -> x.get(cellNum)).collect(Collectors.toList()))
							.trim() + i.trim()).collect(Collectors.toList()));
			map.put(rowNum + "", conditionExpre);
		}
	}
	
	/**
	* 描述：解析表达式
	* @Title: doParseExpressValue
	* @param value
	* @param param
	* @return
	* @author weiyongpeng
	* @date  2024年12月27日 下午3:15:28
	 */
	@SuppressWarnings("unchecked")
	private static String doParseExpressValue(String value, Map<String, Object> param) {
		String expressValue = value;
		XDecisionTableEngine xDecisionTableEngine = new XDecisionTableEngine();
		// 处理sql参数 @sqlVar2@|10
		JSONObject inputJson = JSONObject.fromObject(param);
		if (expressValue.contains("@") && ExecRuleHandler.extractStrings(expressValue).stream().filter(s -> s.split("\\.").length >= 2).collect(Collectors.toList()).size() > 0) {
			List<String> sqlVarList = ExecRuleHandler.extractStrings(expressValue).stream().filter(s -> s.split("\\.").length >= 2).collect(Collectors.toList());
			Iterator<String> it = inputJson.keys();
			for (String sqlVar : sqlVarList) {
				String[] sqlSplit = sqlVar.split("\\.");
				// 取出需要对比的字段
				String compareVar = sqlSplit[1];
				List<Object> columnValueList = new ArrayList<>();
				while (it.hasNext()) {
					String key = it.next();
					if (sqlSplit[0].equals(key)) {
						List<Map<String,Object>> listObjectFir = (List<Map<String,Object>>) com.alibaba.fastjson.JSONArray.parse((String)sqlCache.get(key));
						if (CollectionUtils.isEmpty(listObjectFir)) {
							listObjectFir = xDecisionTableEngine.selectRuleSqlParamRes(inputJson, key, param);
						}
						columnValueList = listObjectFir.stream().filter(mapF -> Optional.ofNullable(mapF.get(compareVar)).isPresent()).map(mapV -> {
							return mapV.get(compareVar);
						}).collect(Collectors.toList());
						param.put(sqlVar.replaceAll("\\.", ""), columnValueList);
					}
				}
				expressValue = expressValue.replaceAll("\\@", "").replaceAll("\\.", "");
			}
		}else { // 不包含sql参数的字段
			List<String> sqlVarList = ExecRuleHandler.extractStrings(expressValue).stream().collect(Collectors.toList());
			for (String key : sqlVarList) {
				List<Map<String,Object>> listObjectFir = Optional.ofNullable(sqlCache.get(key)).isPresent() ? 
						(List<Map<String,Object>>) com.alibaba.fastjson.JSONArray.parse((String)sqlCache.get(key)) : 
							xDecisionTableEngine.selectRuleSqlParamRes(inputJson, key, param);
				param.put(key, listObjectFir);
			}
			expressValue = expressValue.replaceAll("\\@", "");
		}
		return expressValue;
	}
	
	/**
	* 描述：查询sql参数
	* @Title: selectRuleSqlParamRes
	* @param inputjson
	* @param key
	* @param env
	* @return
	* @author weiyongpeng
	* @date  2024年12月27日 下午3:15:03
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String,Object>> selectRuleSqlParamRes(JSONObject inputjson, String key, Map<String, Object> env) {
		String sqlexp;
		// 1、查询sql语句，并执行sql select SQLEXP FROM CONFIG WHERE NAME = ${name}; 所以决策入参正常传递
		RuleSqlModelDto sqlInfoMap = remoteRuleModelService.listRuleModelInner(key).getData();
		String dbType = sqlInfoMap.getDbType();
		ConnectionParam connectionParam = JSON.parseObject(sqlInfoMap.getConnectionParams(), ConnectionParam.class);
		sqlexp = sqlInfoMap.getSqlexp();
		Iterator<String> its = inputjson.keys();
		if(sqlexp.contains("${")) { // 如果有条件参数
			while (its.hasNext()) {
				String key2 = its.next(); 
				if(!key2.equals("everyNodeList") && !key2.equals("areaInfo")) {
					String tmp = "\\$\\{" + key2 + "\\}";
					sqlexp = sqlexp.replaceAll(tmp , "'"+inputjson.getString(key2)+"'");
				}
			}
		}
		// 执行sql获取结果json
		ConnectionProvider connectionProvider = DataSourceUtils.getJdbcTemplate(DbType.getDbType(dbType), connectionParam);
		PreparedStatement prepareStatement;
		try {
			prepareStatement = connectionProvider.getConnection().prepareStatement(sqlexp);
			// 2、转化结果集为json 调用字符串的函数 决策设置需要标识出sql参数 加一个#标识 并缓存
			String sqlStr = (String) Optional.ofNullable(sqlCache.get(key))
											.orElse(putCacheValue(key, JSON.toJSONString(prepareStatement.executeQuery(sqlexp)), DEFAULT_EXPIRE));
			env.put(key, sqlStr);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return (List<Map<String,Object>>) com.alibaba.fastjson.JSONArray.parse((String)sqlCache.get(key));
	}
}
